<template>
  <div class="condition" v-if="isShowConditionQA">
    <div class="top">
      <!--<affix :label="$t('qualityCheck.condition')"></affix>-->
      <div class="tem">
        <span class="temp">{{$t('qualityCheck.qualityTemplateClass')}}：</span>
        <el-radio-group v-model="webOrCallTemp" @change="tempStateChange">
          <el-radio :label="1">{{$t('qualityCheck.qualityTemplateClassCall')}}</el-radio>
          <el-radio :label="2">{{$t('qualityCheck.qualityTemplateClassWeb')}}</el-radio>
        </el-radio-group>
      </div>
      <div class="tem">
        <span class="temp">{{$t('qualityCheck.quaTemp')}}：</span>
        <el-select style="margin-left: 42px;" v-model.trim="chenkTemValue" @change="checkTemChange" v-if="qualityCheckTemplates.length!==0">
          <el-option
            v-show="webOrCallTemp === 2?item.QUALITY_TYPE === 'qualityWebchat':item.QUALITY_TYPE !== 'qualityWebchat'"
            v-for="(item, index) in qualityCheckTemplates"
            :key="index"
            :label="item.name"
            :value="index">
          </el-option>
        </el-select>
        <!--<el-radio-group v-model.trim="chenkTemValue" @change="checkTemChange" v-if="qualityCheckTemplates.length!==0">-->
          <!--<el-radio size="mini"-->
            <!--name="checkTem"-->
            <!--v-show="webOrCallTemp === 2?item.QUALITY_TYPE === 'qualityWebchat':item.QUALITY_TYPE !== 'qualityWebchat'"-->
            <!--v-for="(item, index) in qualityCheckTemplates"-->
            <!--:label="index">-->
              <!--{{item.name}}-->
          <!--</el-radio>-->
        <!--</el-radio-group>-->
        <span v-else>{{$t('qualityCheck.pleaseExployModel')}}</span>
      </div>
      <div class="term" v-show="!isHaveData">
        <p class="temp">{{$t('qualityCheck.conditionalTempl')}}：</p>
        <el-select style="margin-left: 42px;" v-model.trim="conditionTemValue" @change="conditionTemChange">
          <el-option
            v-for="(item, index) in qualityConditionTemplatesDone"
            :key="index"
            :label="item.TEMPLATE_NAME"
            :value="index">
          </el-option>
        </el-select>
        <!--<el-radio-group v-model.trim="conditionTemValue" @change="conditionTemChange" v-show="qualityConditionTemplatesDone.length !== 0">-->
          <!--<el-radio size="mini"-->
                    <!--name="conditionTem"-->
                    <!--v-show="false"-->
                    <!--:label="-1">-->
          <!--</el-radio>-->
          <!--<el-radio size="mini"-->
            <!--name="conditionTem"-->
                    <!--v-show="false"-->
                    <!--:label="-1">-->
          <!--</el-radio>-->
          <!--<el-radio size="mini"-->
            <!--name="conditionTem"-->
            <!--v-for="(item, index) in qualityConditionTemplatesDone"-->
            <!--:label="index">-->
              <!--{{item.TEMPLATE_NAME}}-->
          <!--</el-radio>-->
        <!--</el-radio-group>-->
        <el-button class="addOrDel" @click="showAddCondTemp"><i class="iconfont icon-zhankai"></i> <span>{{$t('qualityCheck.addTempl')}}</span></el-button>
        <el-button v-show="qualityConditionTemplatesDone.length !== 0" class="addOrDel" @click="delCondTemp"><i class="iconfont icon-guanbi"></i> <span>{{$t('qualityCheck.delTempl')}}</span></el-button>
        <el-button v-show="isShowRefresh === 'extraction'" class="addOrDel" @click="refreshCondTemp"><i class="iconfont icon-shuaxin"></i> <span>{{$t('public.refreshExtraction')}}</span></el-button>
        <span class="ui-unfold-span" v-if="qualityConditionTemplatesDone.length !== 0">
          <span @click="isShowFold = false" v-show="isShowFold">{{$t('report.foldedContition')}} <i class="el-icon-arrow-up"></i></span>
          <span @click="isShowFold = true" v-show="!isShowFold">{{$t('report.unfoldedContition')}} <i class="el-icon-arrow-down"></i></span>
        </span>
      </div>
      <Unfold :title="unfoldTitle" :isShow="isShowFold" style="margin-bottom: 20px" v-if="qualityConditionTemplatesDone.length !== 0">
        <template slot="unfoldSlot">
          <div class="condition-temp-show-wrap" v-show="qualityConditionTemplatesDone.length !== 0 && !isHaveData">
            <!--在线咨询条件模板-->
            <div v-show="curQualilyType === 'qualityWebchat' && conditionTemValue !== -1" class="condition-temp-show-webchat">
              <el-row class="random-elrow" :gutter="40" style="margin-top:0px;">
                <el-col :span="8" style="padding-right: 60px;">
                  <p class="wd100">{{$t('qualityCheck.templateName')}}：</p>
                  <div class="condition-temp-con condition-temp-con-first-line">
                    <span class="condition-temp-con-detail">{{curConditionTemp.TEMPLATE_NAME}}</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <p class="wd100">{{$t('qualityCheck.extractRules')}}：</p>
                  <div class="condition-temp-con">
                    <span class="condition-temp-con-detail" style="width: 72%">{{curConditionTemp.suijiLabel}}</span>
                    <span class="condition-temp-con-detail" style="width: 10%">{{curConditionTemp.suijiLabelRandomNum}}</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <p class="wd100">{{$t('webchat.takeTime')}}：</p>
                  <div class="condition-temp-con">
                    <span class="condition-temp-con-detail" style="width:38%;margin:0;">{{curConditionTemp.beginTimeBegin}}</span><span style="padding: 0 6px;"> {{$t('public.to')}} </span><span class="condition-temp-con-detail" style="width:38%;margin:0;">{{curConditionTemp.beginTimeEnd}}</span>
                  </div>
                </el-col>
              </el-row>
              <el-row class="random-elrow" :gutter="40">
                <el-col :span="8" style="padding-right: 60px;">
                  <p class="wd100">{{$t('qualityCheck.endTheSessionType')}}：</p>
                  <div class="condition-temp-con">
                    <span class="condition-temp-con-detail">{{curConditionTemp.finishKeys}}</span>
                  </div>
                </el-col>
                <el-col :span="8" style="padding-right:60px;">
                  <p class="wd100">{{$t('webchat.platformSource')}}：</p>
                  <div class="condition-temp-con condition-temp-con-first-line">
                    <span class="condition-temp-con-detail" style="width: 100%">{{curConditionTemp.platform}}</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <p class="wd100">{{$t('webchat.msgNum')}}：</p>
                  <div class="condition-temp-con random-condition-temp-con">
                    <el-radio v-model="curConditionTemp.msgCountType" label="gt" size="mini" :disabled="true">{{$t('public.moreThan')}}</el-radio>
                    <el-radio v-model="curConditionTemp.msgCountType" label="lt" :disabled="true" size="mini">{{$t('public.lessThan')}}</el-radio>
                    <el-radio v-model="curConditionTemp.msgCountType" label="eq" size="mini" :disabled="true">{{$t('public.equal')}}</el-radio>
                    <span class="condition-temp-con-detail" style="width: 60px;margin-left:10px;">{{curConditionTemp.msgCount}}</span>
                  </div>
                </el-col>
              </el-row>
              <el-row class="random-elrow" :gutter="40">
                <el-col :span="8" style="padding-right: 60px;">
                  <p class="wd100">{{$t('public.satisfaction')}}：</p>
                  <div class="condition-temp-con condition-temp-con-first-line">
                    <span class="condition-temp-con-detail">{{curConditionTemp.satisfaction}}</span>
                  </div>
                </el-col>
                <el-col :span="16">
                  <p class="wd100">{{$t('qualityCheck.agentForQua')}}：</p>
                  <div class="condition-temp-con condition-temp-con-last-line">
                    <span v-show="curConditionTemp.agents && curConditionTemp.agents.length === 0" class="condition-temp-con-detail" style="width: 20%">{{curConditionTemp.agentsInput}}</span>
                    <div style="display: inline-block;width:70%;"><el-tag size="medium" style="margin-right:6px;margin-bottom:4px;" v-for="(item, index) in curConditionTemp.agents" :key="index">{{item}}</el-tag><el-checkbox  v-model="curConditionTemp.checkState" :disabled="true">{{$t('public.includeUnderAgent')}}</el-checkbox></div>
                  </div>
                </el-col>
              </el-row>
            </div>
            <!--通话条件模板-->
            <div v-show="curQualilyType !== 'qualityWebchat' && conditionTemValue !== -1" class="condition-temp-show-call">
              <el-row class="random-elrow" :gutter="40" style="margin-top:0px;">
                <el-col :span="8" style="padding-right: 60px;">
                  <p class="wd100">{{$t('qualityCheck.templateName')}}：</p>
                  <div class="condition-temp-con condition-temp-con-first-line">
                    <span class="condition-temp-con-detail" style="width: 100%">{{curConditionTemp.TEMPLATE_NAME}}</span>
                  </div>
                </el-col>
                <el-col :span="8" style="padding-right:60px;">
                  <p class="wd100" style="width:160px;">{{curConditionTemp.suijiLabel}}：</p>
                  <div class="condition-temp-con condition-temp-con-first-line">
                    <span class="condition-temp-con-detail">{{curConditionTemp.suijiLabelRandomNum}}</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <p class="wd100">{{$t('call.callTime')}}：</p>
                  <div class="condition-temp-con">
                    <span class="condition-temp-con-detail" style="width:40%;margin-right:0;">{{curConditionTemp.CALL_TIME_LENGTH_BEGIN}}<span class="second">{{$t('public.seconds')}}</span></span><span style="padding: 0 6px;"> {{$t('public.to')}} </span><span class="condition-temp-con-detail" style="width:40%;margin-right: 0;overflow: hidden;">{{curConditionTemp.CALL_TIME_LENGTH_END}}<span class="second">{{$t('public.seconds')}}</span></span>
                  </div>
                </el-col>
              </el-row>
              <el-row class="random-elrow" :gutter="40">
                <el-col :span="8" style="padding-right: 60px;">
                  <p class="wd100">{{$t('public.satisfaction')}}：</p>
                  <div class="condition-temp-con condition-temp-con-first-line">
                    <span class="condition-temp-con-detail" style="width: 100%">{{curConditionTemp.INVESTIGATE}}</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <p class="wd100">{{$t('public.callLabel')}}：</p>
                  <div class="condition-temp-con" style="width:100%;">
                    <span class="condition-temp-con-detail" style="width: calc(100% - 40px)">{{curConditionTemp.qaLableOne}}</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <p class="wd100">{{$t('public.callTime')}}：</p>
                  <div class="condition-temp-con">
                    <span class="condition-temp-con-detail" style="width:40%;margin:0;">{{curConditionTemp.BEGIN_TIME}}</span><span style="padding: 0 6px;"> {{$t('public.to')}} </span><span class="condition-temp-con-detail" style="width:40%;margin:0;">{{curConditionTemp.END_TIME}}</span>
                  </div>
                </el-col>
              </el-row>
              <el-row class="random-elrow" :gutter="40">
                <el-col :span="8" style="padding-right: 60px;" v-show="callAgentShow">
                  <p class="wd100">{{$t('qualityCheck.callAgent')}}：</p>
                  <div class="condition-temp-con">
                    <span v-show="curConditionTemp.agents && curConditionTemp.agents.length === 0" class="condition-temp-con-detail" style="width: 100%">{{curConditionTemp.agentsInput}}</span>
                    <div style="display: inline-block;"><el-tag size="medium" style="margin-right:6px;margin-bottom:4px;" v-for="(item, index) in curConditionTemp.agents" :key="index">{{item}}</el-tag></div>
                    <!--<el-checkbox v-model="curConditionTemp.checkState" :disabled="true">{{$t('public.includeUnderAgent')}}</el-checkbox>-->
                  </div>
                </el-col>
                <el-col :span="8" style="padding-right: 60px;">
                  <p class="wd100" style="vertical-align: top;">{{$t('call.callType')}}：</p>
                  <div class="condition-temp-con">
                    <span v-show="curConditionTemp.selectedCallTypeList && curConditionTemp.selectedCallTypeList.length === 0" class="condition-temp-con-detail" style="width: 100%">{{curConditionTemp.selectedCallTypeAll}}</span>
                    <div style="display: inline-block;width: 100%;"><el-tag size="medium" style="margin-right:6px;margin-bottom:4px;" v-for="(item, index) in curConditionTemp.selectedCallTypeList" :key="index">{{item}}</el-tag></div>
                  </div>
                </el-col>
                <el-col :span="8">
                  <p class="wd100" style="vertical-align: top;">{{$t('public.queues')}}：</p>
                  <div class="condition-temp-con">
                    <span v-show="curConditionTemp.myqueue && curConditionTemp.myqueue.length === 0" class="condition-temp-con-detail" style="width: 100%">{{curConditionTemp.ERROR_MEMO}}</span>
                    <el-tag size="medium" style="margin-right:6px;margin-bottom:4px;" v-for="(item, index) in curConditionTemp.myqueue" :key="index">{{item}}</el-tag>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
        </template>
      </Unfold>
      <div class="sub">
        <el-button :disabled="isShowRefresh === 'extraction'" @click="resetSearchByCoditionTemBtn" class="primary_btn report_excel_btn">{{$t('qualityCheck.reExtract')}}</el-button>
        <el-button :disabled="isShowRefresh === 'extraction'" type="primary" class="search primary_btn" @click="queryList">{{$t('public.search2')}}</el-button>
      </div>
      <affix :label="$t('public.searchResult')"></affix>
    </div>
    <div class="tables" v-show="qualityConditionTemplatesDone.length !== 0 && !isHaveData && conditionTemValue !== -1 && isShowRefresh !== 'extraction' && isShowRefresh !== 'unextraction'" v-loading="webLoading || callLoading">
      <div class="deploy" v-show="qualityConditionTemplatesDone.length !== 0">
        <div class="table-header-config">
          <i class="iconfont icon-peizhi"></i>
          <span class="tex" @click.stop="setHeaderConfig">{{$t('report.setHeaderConfig')}}</span>
        </div>
        <Pagination
          v-show="curQualilyType === 'qualityWebchat' && isShowTable"
          class="fr"
          :small="true"
          :currentPage="webCurPage"
          :count="count"
          @turnPage="turnPageWebchat"
          :totalPage="Math.ceil(count/pageSize)"
        >
        </Pagination>
        <Pagination
          v-show="curQualilyType !== 'qualityWebchat' && isShowTable"
          class="fr"
          :small="true"
          :currentPage="callCurPage"
          :count="count"
          @turnPage="turnPageCall"
          :totalPage="Math.ceil(count/pageSize)"
        >
        </Pagination>
      </div>
      <el-table :data="tableData" size="mini">
        <el-table-column
          :width="item.name === 'OFFERING_TIME' ? '160' : ''"
          :show-overflow-tooltip="true"
          v-for="(item, index) in tableDataHeader.Config"
          :key="index"
          v-if="item.show === true"
          :prop="item.name"
          :label="item.displayname">
        </el-table-column>
        <el-table-column :label="$t('public.operate')" width="160">
          <template scope="scope2">
            <el-button @click="handle(scope2.row)" type="text" size="small">{{$t('qualityCheck.grade')}}</el-button>
            <el-button @click="replacementRecord(scope2.row)" type="text" size="small">{{$t('qualityCheck.replacement')}}</el-button>
            <el-button type="text" @click="look(scope2.row._id)" size="small" >{{$t('qualityCheck.viewLook')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="text-align: center;padding: 20px;">
      <!--<span v-show="isHaveData || qualityConditionTemplatesDone.length === 0">{{$t('public.noData')}}</span><br/>-->
      <!--<span v-show="(!isSearchState || conditionTemValue === -1) && isShowRefresh !== 'extraction' && isShowRefresh !== 'unextraction'">{{$t('public.pleaseSearch')}}</span><br/>-->
      <span v-show="isShowRefresh === 'extraction'">{{$t('public.extraction')}}</span><br/>
      <span v-show="isShowRefresh === 'unextraction'">{{$t('public.unextraction')}}</span>
    </div>
    <div class="looklog">
      <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :visible.sync="isShowlooklog" :title="title">
        <div class="tables">
          <div class="deploy">
            <div class="search-pagination">
              <pagination
                :small="paginationRecord.small"
                :currentPage="paginationRecord.currentPage"
                :count="countRecord"
                @turnPage="turnPageRecord"
                :totalPage="totalPageRecord"
              >
              </pagination>
            </div>
          </div>
          <el-table :data="recordList" style="width: 100%" size="mini">
            <el-table-column prop="user" :label="listenpp" width="">
            </el-table-column>
            <el-table-column prop="" label="" width="">
            </el-table-column>
            <el-table-column prop="time" :label="listenTime" width="">
            </el-table-column>
          </el-table>
        </div>
      </el-dialog>
    </div>
    <!-- 通话质检  评分 -->
      <call-grade :callDialogShow="callDialogShow" v-if="callIsShow" @close="off" :flagId="flagId" :currentItemCall = "this.currentItemCall"  :currentGrade = "{}"  :template = "this.template" @saveGrade="saveGrade" @nextGrade="nextGrade" :qcResectLabel="qcResectLabel" @off="off" @handle="handle" :refreshCallGrade="refreshCallGrade"></call-grade>
    <!-- 在线客服质检 评分-->
      <webchat-grade :webchatDialogShow="webchatDialogShow" v-if="webChatIsShow" @close="off" :currentItem = "this.currentItem" :currentGrade = "{}" :currentItemWebchat = "this.currentItemWebchat" :template = "this.template" @off="off" @saveGrade="saveGrade" @nextGrade="nextGrade" @handle="handle"></webchat-grade>
    <!--添加模板组件-->
    <add-condition @addConditionTem="addConditionTem" :addCondTemData="addCondTemData"></add-condition>
    <!--配置表头-->
    <header-option v-show="isShowTableConfig" :show="isShowTableConfig" :option="headOptions" :type="tableConfigType" v-on:close="closeTableConfig"></header-option>
  </div>
</template>
<script>
  import {deepClone, getCache, getLabelName, initFinishName, isHasFunc} from '@/utils/m7Utils'
  import addCondition from '../base/addConditionTem'
  import CallGrade from './CallGrade'
  import WebchatGrade from './WebchatGrade'
  import Pagination from '@/components/public-modules/card/Pagination'
  import Affix from '../../../ui-modules/affix/Affix.vue'
  import Unfold from '../../../ui-modules/unfold/index.vue'
  import bus from '@/store/eventBus'
  import headerOption from '../../report/base/headerOption.vue'
  export default {
    name: 'random',
    props: {
      refresh: String
    },
    data () {
      return {
        webOrCallTemp: 1,
        isShowConditionQA: false,
        beforeMountState: false,   //   beforemount 时 不查数据  避免各模块  数据冲突
        channelDic: [],
        queues: [],
        platforms: [
          {label: this.$t('webchat.websiteCon'), value: 'pc'},
          {label: this.$t('webchat.wapCon'), value: 'wap'},
          {label: this.$t('webchat.appCon'), value: 'sdk'},
          {label: this.$t('webchat.weChatCon'), value: 'weixin'},
          {label: this.$t('webchat.weChatMini'), value: 'wxmini'},
          {label: this.$t('webchat.weBoCon'), value: 'weibo'},
          {label: this.$t('webchat.enterpriseShot'), value: 'wxwork'},
          {label: this.$t('webchat.baiduBCP'), value: 'ocpc'},
          {label: this.$t('webchat.TikTok'), value: 'dy'},
          {label: this.$t('webchat.platformWXKF'), value: 'wxkf'}
        ],
        callLabel: [],
        agents: [],
        options: [],
        webchatDataIdList: {},    //    已经被置换过的数据的id的集合
        callDataIdList: {},       //    已经被置换过的数据的id的集合
        qualityCheckTemplates: [],
        chenkTemValue: 0,   //   质检模板  value
        num: 0,   //   质检模板  临时变量
        once: true,
        isHaveData: false,  //   暂无数据 提示框 是否展示
        isSearchState: false,  //   暂无数据 提示框 是否展示
        conditionTemValue: '',   //   条件模板  value
        conditionTempId: '',    //    条件模板  id
        qualityConditionTemplates: [],   //   质检条件模板
        qualityWebchatConditionTemplates: [],   //   质检条件模板--在线咨询
        qualityCallConditionTemplates: [],   //   质检条件模板--通话
        qualityConditionTemplatesDone: [],   //   渲染在页面的 条件模板
        curConditionTemp: {},    //  当前被选中的 条件模板对象
        curQualilyType: 'qualityWebchat',   //   质检还是通话
        webCurPage: 1,
        callCurPage: 1,
        currentItemWebchat: {},
        pageSize: 10,
        webLoading: false,
        callLoading: false,
        callAgentShow: false,    // 是否有显示座席信息权限
        isShowTable: false,
        resetState: false,
        isShowRefresh: 'finish',    //  条件模板  是否抽取成功时  刷新按钮是否展示
        addCondTemData: {    //    添加条件模板  dialog  传的数据
          isShow: false
        },
        isShowlooklog: false,    // 显示查看日志
        recordList: [],
        paginationRecord: {
          small: false,
          currentPage: 1
        },
        template: {},
        callDialogShow: false,     // 评分
        webchatDialogShow: false,     // 评分
        isSave: false,
        qcResectLabel: false,
        currentItemCall: {},   //   评分组件  用
        currentItem: {},    //   评分组件  用
        refreshCallGrade: 0,
        flagId: 'random',
        title: '',
        listenTime: '',
        listenpp: '',
        countRecord: 0,
        totalPageRecord: 1,
        tableData: [],
        tableDataHeader: {
          Config: [{ 'order': '1', 'name': 'CALL_NO_SHOW', 'displayname': '主叫号码', 'show': true }, { 'order': '2', 'name': 'DISPOSAL_AGENT', 'displayname': '接听座席', 'show': true }, { 'order': '3', 'name': 'CALLED_NO_SHOW', 'displayname': '被叫号码', 'show': true }, { 'order': '4', 'name': 'CONNECT_TYPE_show', 'displayname': '呼叫类型', 'show': true }, { 'order': '5', 'name': 'ERROR_MEMO', 'displayname': '呼入技能组', 'show': true }, { 'order': '6', 'name': 'INVESTIGATE', 'displayname': '满意度', 'show': true }, { 'order': '7', 'name': 'OFFERING_TIME', 'displayname': '呼叫时间', 'show': true }]
        },
        unfoldTitle: [], // 展开收起标题
        isShowFold: true, // 展开收起标题
        callIsShow: false, // 通话评分
        webChatIsShow: false, // 在线咨询评分
        isShowTableConfig: false, // 配置表头
        headOptions: {},    //  配置表头
        tableConfigType: 'quality_call_table_title'
      }
    },
    components: {
      addCondition,
      Pagination,
      CallGrade,
      WebchatGrade,
      Affix,
      Unfold,
      headerOption
    },
    watch: {
      refresh (cur, old) {
        if (cur === 'random') {
//          this.searchByCoditionTemBtn()
        }
      }
    },
    methods: {
//        添加模板 弹窗
      showAddCondTemp () {
        this.addCondTemData.isShow = true
        this.addCondTemData.curQualilyType = this.curQualilyType
      },
//      添加条件模板
      addConditionTem (addTempState) {
        this.$store.dispatch('getCache', {type: 'qualityConditionTemplates', loadFromServer: true}).then(() => {
          this.qualityConditionTemplates = deepClone(this.$getCache('qualityConditionTemplates'))
          //          在线咨询的条件模板
          this.qualityWebchatConditionTemplates = this.qualityConditionTemplates.filter(item => {
            if (item.QUALITY_TYPE && item.QUALITY_TYPE === 'qualityWebchat') {
              return item
            }
          })
          //          通话的条件模板
          this.qualityCallConditionTemplates = this.qualityConditionTemplates.filter(item => {
            if (!item.QUALITY_TYPE) {
              return item
            }
          })
          if (this.webOrCallTemp === 1) {
            //   条件模板
            this.curQualilyType = 'qualityCall'
            this.qualityConditionTemplatesDone = this.qualityCallConditionTemplates
          } else {
            //   条件模板
            this.curQualilyType = 'qualityWebchat'
            this.qualityConditionTemplatesDone = this.qualityWebchatConditionTemplates
          }
          this.conditionTemValue = 0
          this.conditionTemChange(0)
        })
//        if (addTempState === 'addAndSelect') {
//          this.resetState = true
//          this.fetchData()
//        } else {
//          this.fetchData()
//        }
        this.addCondTemData.isShow = false
      },
//      删除条件模板
      delCondTemp () {
        if (this.conditionTemValue === -1) {
          this.$message.error(this.$t('qualityCheck.chooseRandomTem'))
          return
        }
        let data = {}
        let self = this
        data.randomTemplate = this.conditionTempId
        this.$confirm(this.$t('qualityCheck.confirmDelTempl'), this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('removeQualityCheckRandomTemplates', data).then(res => {
            if (res) {
              this.addConditionTem()    //   刷新条件模板 名字没改
//              this.$store.dispatch('getCache', {type: 'qualityConditionTemplates', loadFromServer: true}).then(() => {
//                if (this.qualityConditionTemplatesDone.length > 0) {
//                  this.conditionTemValue = 0
//                  this.conditionTemChange(0)
//                }
//              })
              self.$message({
                message: this.$t('qualityCheck.delTemplSuccess'),
                type: 'success'
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('sms.cancelDel')
          })
        })
      },
//      刷新条件模板  抽取状态
      refreshCondTemp () {
        this.$store.dispatch('refreshCallExtractionStatus', {type: 'random', templateId: this.conditionTempId}).then(res => {
          if (!res.extractionStatus || res.extractionStatus === 'finish') {
            this.searchByCoditionTemBtn()
            this.isShowRefresh = 'finish'
          }
        })
      },
//      从缓存获取 质检模板
      fetchData () {
        let p1 = this.$store.dispatch('getCache', {type: 'qualityCheckTemplates'})
        let p2 = this.$store.dispatch('getCache', {type: 'qualityConditionTemplates', loadFromServer: true})
        let p3 = this.$store.dispatch('getCache', {type: 'options'})
        let p4 = this.$store.dispatch('getCache', {type: 'channelDic'})
        let p5 = this.$store.dispatch('getCache', {type: 'queues'})
        let p6 = this.$store.dispatch('getCache', {type: 'callLabel'})
        let p7 = this.$store.dispatch('getCache', {type: 'agents'})
        Promise.all([p1, p2, p3, p4, p5, p6, p7]).then(() => {
          this.qualityCheckTemplates = this.$getCache('qualityCheckTemplates')
          this.qualityConditionTemplates = deepClone(this.$getCache('qualityConditionTemplates'))
  //          在线咨询的条件模板
          this.qualityWebchatConditionTemplates = this.qualityConditionTemplates.filter(item => {
            if (item.QUALITY_TYPE && item.QUALITY_TYPE === 'qualityWebchat') {
              return item
            }
          })
  //          通话的条件模板
          this.qualityCallConditionTemplates = this.qualityConditionTemplates.filter(item => {
            if (!item.QUALITY_TYPE) {
              return item
            }
          })
          this.options = this.$getCache('options')
          this.channelDic = this.$getCache('channelDic')
          this.queues = this.$getCache('queues')
          this.callLabel = this.$getCache('callLabel')
          this.agents = this.$getCache('agents')
          if (this.qualityCheckTemplates.length > 0) {
//            this.chenkTemValue = 0
            this.tempStateChange()
//            this.checkTemChange(this.num)
          }
          this.isShowConditionQA = true
        })
      },
//      质检模板分类 change
      tempStateChange () {
        this.isHaveData = true
        this.isSearchState = false
        if (this.webOrCallTemp === 1) {
          this.qualityCheckTemplates.some((item, index) => {
            if (item.QUALITY_TYPE !== 'qualityWebchat') {
              this.num = index
              this.isHaveData = false
              return item.QUALITY_TYPE !== 'qualityWebchat'
            }
          })
          //   条件模板
          this.curQualilyType = 'qualityCall'
          this.qualityConditionTemplatesDone = this.qualityCallConditionTemplates
        } else {
          this.qualityCheckTemplates.some((item, index) => {
            if (item.QUALITY_TYPE === 'qualityWebchat') {
              this.num = index
              this.isHaveData = false
              return item.QUALITY_TYPE === 'qualityWebchat'
            }
          })
          //   条件模板
          this.curQualilyType = 'qualityWebchat'
          this.qualityConditionTemplatesDone = this.qualityWebchatConditionTemplates
        }
        this.chenkTemValue = this.num
        this.checkTemChange(this.chenkTemValue)
        this.conditionTemValue = 0
        this.conditionTemChange(0)
        this.isShowRefresh = 'finish'
        if (this.once) {
          this.once = false
        }
      },
//      质检模板 radio change事件
      checkTemChange (index) {
//        this.isShowTable = false
        if (this.qualityCheckTemplates.length) {
          this.template = this.qualityCheckTemplates[index]
//          if (this.qualityCheckTemplates[index].QUALITY_TYPE === 'qualityWebchat') {
//            this.curQualilyType = 'qualityWebchat'
//            this.qualityConditionTemplatesDone = this.qualityWebchatConditionTemplates
//          } else {
//            this.curQualilyType = 'qualityCall'
//            this.qualityConditionTemplatesDone = this.qualityCallConditionTemplates
//          }
//          if (this.qualityConditionTemplatesDone.length > 0) {
//            if (this.resetState) {
//              this.conditionTemValue = 0
//              this.conditionTemChange(0)
//            } else {
//              this.conditionTemValue = -1
//              this.conditionTemChange(-1)
//            }
//          }
        }
      },
//      条件模板  radio change 事件        ===================================
      conditionTemChange (index) {
        if (index === -1) {
          this.isSearchState = false
          return
        }
        this.isSearchState = false
        if (this.qualityConditionTemplatesDone && this.qualityConditionTemplatesDone.length === 0) {
          return
        }
        this.conditionTempId = this.qualityConditionTemplatesDone[index]._id
        this.curConditionTemp = {}
        let curConditionTempCall = {}
        let curCond = this.qualityConditionTemplatesDone[index]
        console.log(JSON.stringify(this.curConditionTemp))
        curConditionTempCall.TEMPLATE_NAME = curCond.TEMPLATE_NAME
        //          随机抽取数
        let randomRule = curCond[curCond.EXT_RULE]
        let label = this.$t('qualityCheck.perCapitaRandomNum')
        let randomNum = 0
        if (randomRule === 'per_num') {
          label = this.$t('qualityCheck.perCapitaRandomNum')
          randomNum = curCond.TEMPLATE_NUM
        } else if (randomRule === 'per_percent') {
          label = this.$t('qualityCheck.perCapitaRandomPer')
          randomNum = curCond.PERCENT + '%'
        } else if (!randomRule || randomRule === 'entirety_num') {
          label = this.$t('qualityCheck.wholeCapitaRandomNum')
          randomNum = curCond.TEMPLATE_NUM
        } else if (randomRule === 'entirety_percent') {
          label = this.$t('qualityCheck.wholeCapitaRandomPer')
          randomNum = curCond.PERCENT + '%'
        }
        curConditionTempCall.suijiLabel = label
        curConditionTempCall.suijiLabelRandomNum = randomNum
//          是否包含下级
        if (curCond.includeSubordinate) {
          curConditionTempCall.checkState = true
        } else {
          curConditionTempCall.checkState = false
        }
        if (this.curQualilyType !== 'qualityWebchat') {
//          呼叫类型
          curConditionTempCall.selectedCallTypeList = []
          curConditionTempCall.selectedCallTypeAll = ''
          if (curCond.selectedCallTypeList) {
            let callTypeArr = curCond.selectedCallTypeList.split(',')
            for (let a = 0; a < callTypeArr.length; a++) {
              if (callTypeArr[a] === 'normal') {
                curConditionTempCall.selectedCallTypeList.push(this.$t('qualityCheck.normalCallIn'))
              } else if (callTypeArr[a] === 'dialout') {
                curConditionTempCall.selectedCallTypeList.push(this.$t('qualityCheck.callOut'))
              } else if (callTypeArr[a] === 'transfer') {
                curConditionTempCall.selectedCallTypeList.push(this.$t('qualityCheck.callInTrans'))
              } else if (callTypeArr[a] === 'dialTransfer') {
                curConditionTempCall.selectedCallTypeList.push(this.$t('qualityCheck.callOutTrans'))
              }
            }
          } else {
            curConditionTempCall.selectedCallTypeAll = this.$t('qualityCheck.all')
          }
//          通话时长
          curConditionTempCall.CALL_TIME_LENGTH_BEGIN = curCond.query.CALL_TIME_LENGTH_BEGIN ? curCond.query.CALL_TIME_LENGTH_BEGIN : ''
          curConditionTempCall.CALL_TIME_LENGTH_END = curCond.query.CALL_TIME_LENGTH_END ? curCond.query.CALL_TIME_LENGTH_END : ''
//            呼叫时间
          curConditionTempCall.BEGIN_TIME = curCond.query.BEGIN_TIME
          curConditionTempCall.END_TIME = curCond.query.END_TIME
//          满意度
          curConditionTempCall.INVESTIGATE = ''
          let investigate = this.getinvestigate()
          if (curCond.query.INVESTIGATE) {
            let investiageNum = curCond.query.INVESTIGATE
            if (investiageNum === 'unevaluated') {
              curConditionTempCall.INVESTIGATE = '--' + this.$t('public.unevaluated') + '--'
            } else if (investiageNum) {
              for (let i = 0; i < investigate.options.length; i++) {
                let invData = investigate.options[i]
                for (let j = 0; j < invData.options.length; j++) {
                  if (invData.options[j].name === investiageNum) {
                    curConditionTempCall.INVESTIGATE = invData.name
                  }
                }
              }
            }
          }
//          技能组
          curConditionTempCall.myqueue = []
          curConditionTempCall.ERROR_MEMO = ''
          if (curCond.selectedQueueList) {
            let queues = this.queues
            let queueArr = curCond.selectedQueueList.split(',')
            for (let i = 0; i < queues.length; i++) {
              for (let a = 0; a < queueArr.length; a++) {
                if (queues[i].Exten === queueArr[a]) {
                  curConditionTempCall.myqueue.push(queues[i].DisplayName)
                }
              }
            }
            for (let i = 0; i < queues.length; i++) {
              if (queues[i].Exten === curCond.query.ERROR_MEMO) {
                curConditionTempCall.ERROR_MEMO = queues[i].DisplayName
              }
            }
          } else {
            curConditionTempCall.myqueue.push(this.$t('public.all'))
          }
//          录音标签
          curConditionTempCall.qaLableOne = ''
          let callLabel = this.callLabel
          if (curCond.query.singleLabel) {
            for (let i in callLabel) {
              if (callLabel[i]._id === curCond.query.singleLabel) {
                curConditionTempCall.qaLableOne = callLabel[i].name
              }
            }
          } else if (curCond.query.multiLabel) {
            let multiLabel = curCond.query.multiLabel || []
            let labelStr = ''
            labelStr += getLabelName(multiLabel, callLabel, labelStr)
            labelStr = labelStr.substring(0, labelStr.length - 1)
            curConditionTempCall.qaLableOne = labelStr
          }
//          通话座席
          let disposalAgent = curCond.query.DISPOSAL_AGENT
          curConditionTempCall.agents = []
          curConditionTempCall.agentsInput = ''
          if (!randomRule && disposalAgent) {
            let agents = this.agents
            if (typeof disposalAgent === 'object') {
              for (let i = 0; i < agents.length; i++) {
                for (let a = 0; a < disposalAgent.length; a++) {
                  if (agents[i]._id === disposalAgent[a]) {
                    curConditionTempCall.agents.push(agents[i].displayName)
                  }
                }
              }
            } else {
              for (let i = 0; i < agents.length; i++) {
                if (agents[i]._id === disposalAgent) {
                  curConditionTempCall.agents.push(agents[i].displayName)
                }
              }
            }
          } else if (curCond.selectedAgentList && curCond.selectedAgentList !== '') {
            let agents = this.agents
            let disposalAgentArr = curCond.selectedAgentList.split(',')
            for (let i = 0; i < agents.length; i++) {
              for (let a = 0; a < disposalAgentArr.length; a++) {
                if (agents[i]._id === disposalAgentArr[a]) {
                  curConditionTempCall.agents.push(agents[i].displayName)
                }
              }
            }
          } else {
            curConditionTempCall.agentsInput = this.$t('qualityCheck.all')
          }
        }
        if (this.curQualilyType === 'qualityWebchat') {
//          领取时间
          curConditionTempCall.beginTimeBegin = curCond.query.beginTimeBegin ? curCond.query.beginTimeBegin : ''
          curConditionTempCall.beginTimeEnd = curCond.query.beginTimeEnd ? curCond.query.beginTimeEnd : ''
//          座席
          curConditionTempCall.agents = []
          if (curCond.selectedAgentList && curCond.selectedAgentList !== '') {
            let agents = this.agents
            let disposalAgentArr = curCond.selectedAgentList.split(',')
            for (let i = 0; i < agents.length; i++) {
              for (let a = 0; a < disposalAgentArr.length; a++) {
                if (agents[i]._id === disposalAgentArr[a]) {
                  curConditionTempCall.agents.push(agents[i].displayName)
                }
              }
            }
          } else {
            curConditionTempCall.agentsInput = this.$t('qualityCheck.all')
          }
//          满意度
          curConditionTempCall.satisfaction = ''
          let appraiseKey = curCond.query.appraiseKey ? curCond.query.appraiseKey : ''
          if (appraiseKey === '') {
            curConditionTempCall.satisfaction = ''
          } else if (appraiseKey === 'unevaluated') {
            curConditionTempCall.satisfaction = '--' + this.$t('public.unevaluated') + '--'
          } else {
            let wechatCSR = this.getChannelDic('webchatCSR')
            for (let i = 0; i < wechatCSR.length; i++) {
              if (wechatCSR[i].key === curCond.query.appraiseKey) {
                curConditionTempCall.satisfaction = wechatCSR[i].name
              }
            }
          }
//          结束会话类型
          curConditionTempCall.finishKeys = ''
          let dicsFinish = this.getChannelDic('webchat')
          let finishKeys = []
          for (let i = 0; i < dicsFinish.length; i++) {
            finishKeys.push(dicsFinish[i])
            let level2 = deepClone(dicsFinish[i].options)
            if (level2) {
              for (let m = 0; m < level2.length; m++) {
                level2[m].name = dicsFinish[i].name + '->' + level2[m].name
                finishKeys.push(level2[m])
                let level3 = deepClone(level2[m].options)
                if (level3) {
                  for (let n = 0; n < level3.length; n++) {
                    level3[n].name = level2[m].name + '->' + level3[n].name
                    finishKeys.push(level3[n])
                    let level4 = deepClone(level3[n].options)
                    if (level4) {
                      for (let j = 0; j < level4.length; j++) {
                        level4[n].name = level3[m].name + '->' + level4[n].name
                        finishKeys.push(level4[j])
                        let level5 = deepClone(level4[j].options)
                        if (level5) {
                          for (let k = 0; k < level5.length; k++) {
                            level5[k].name = level4[j].name + '->' + level5[k].name
                            finishKeys.push(level5[k])
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
          finishKeys.push({key: 'add_black', name: this.$t('webchat.addBlacklist')})
          for (let i = 0; i < finishKeys.length; i++) {
            if (finishKeys[i]['key'] === curCond.query.finishKey) {
              curConditionTempCall.finishKeys = finishKeys[i]['name']
            }
          }
//          平台来源
          curConditionTempCall.platform = ''
          this.platforms.forEach(item => {
            if (curCond.query.platform === item.value) {
              curConditionTempCall.platform = item.label
            }
          })
//          消息条数
          curConditionTempCall.msgCountType = curCond.query.msgCountType
          curConditionTempCall.msgCount = curCond.query.msgCount
        }
        this.curConditionTemp = deepClone(curConditionTempCall)
//        条件模板change  查询数据====================================================
        this.isShowRefresh = 'finish'
        if (curCond.extractionStatus === 'extraction') { //  抽取中
          this.isShowRefresh = 'extraction'
          this.$store.dispatch('refreshCallExtractionStatus', {type: 'random', templateId: this.conditionTempId}).then(res => {
            if (!res.extractionStatus || res.extractionStatus === 'finish') {
              this.queryList()
              this.isShowRefresh = 'finish'
            }
          })
        } else if (curCond.extractionStatus === 'unextraction') {  //  未抽取
          this.$message.error(this.$t('qualityCheck.PleaseReExtract'))
          this.isShowRefresh = 'unextraction'
        } else {
          this.queryList()
        }
//        if (!this.beforeMountState) {
//        }
//        this.beforeMountState = false
      },
//      通话  满意度  匹配  条件模板详细信息展示时用到此方法
      getinvestigate () {
        let options = this.options
        for (let i = 0; i < options.length; i++) {
          if (options[i].name === '满意度调查选项') {
            return options[i]
          }
        }
      },
//      在线咨询  满意度  匹配  条件模板详细信息展示时用到此方法
      getChannelDic (type) {
        let dicss = this.channelDic
        let dics = []
        for (let i = 0; i < dicss.length; i++) {
          let obj = dicss[i]
          if (obj.type === type) {
            dics = obj.options || []
            break
          }
        }
        return dics
      },
//      =======================================================
//      查询 核心
      searchByCoditionTem () {
        let data = {}
        this.webLoading = true
        this.callLoading = true
        this.isSave = false
        data.pageSize = this.pageSize
//        如果是 重新抽取功能触发 则加字段 reset
        if (this.resetState) {
          data.reset = true
        }
        if (this.curQualilyType === 'qualityWebchat') {
          data.page = this.webCurPage
          if (this.resetState) {
            data.page = 1
          }
          data.menuId = 'quality_check_query_random'
          data.templateId = this.conditionTempId
          data.searchType = 'random'
          this.$store.dispatch('webchatSearch', data).then(res => {
            this.webLoading = false
            this.callLoading = false
            this.isShowTable = true
            this.isSearchState = true
//            if (res.success) {
            if (this.resetState) {
              this.resetState = false
              this.isShowRefresh = 'extraction'
              this.qualityConditionTemplatesDone.forEach(item => {
                if (item._id === this.conditionTempId) {
                  item.extractionStatus = 'extraction'
                }
              })
            }
            const list = res.list || []
            if (list.length === 0) {
              if (res.more) {
                this.turnPageWebchat(1)
              } else {
                if (!res.count) {
                  // 第一页且count为0是不再发请求
                  this.webCurPage = 1
                } else { // 当前页没有数据了，查最后一页
                  let page = Math.ceil(res.count / data.pageSize)
                  this.turnPageWebchat(page)
                  return false
                }
              }
            }
//            }
            let _dics = []
            for (var i = 0; i < this.channelDic.length; i++) {
              let obj = this.channelDic[i]
              if (obj.type === 'webchat') {
                _dics = obj.options || []
                break
              }
            }
            let finishOptions = initFinishName(_dics, {})
            let listArr = []
            for (let i = 0; i < list.length; i++) {
              let item = deepClone(list[i])
              if (item.finishKey) {
                item.finishReasonTitle = finishOptions[item.finishKey] || ''
              } else {
                item.finishReasonTitle = ''
              }
              listArr.push(item)
            }
            this.tableData = listArr
            this.tableDataHeader = res.tableHeader
          })
        } else {
          data.page = this.callCurPage
          if (this.resetState) {
            data.page = 1
          }
          data.cdrId = 'quality_check_query_random'
          data.randomTemplate = this.conditionTempId
          data.searchType = 'random'
          this.$store.dispatch('normalCallSearch', data).then(res => {
            this.webLoading = false
            this.callLoading = false
            this.isShowTable = true
            this.isSearchState = true
//            if (res.success) {
            if (this.resetState) {
              this.resetState = false
              this.isShowRefresh = 'extraction'
              this.qualityConditionTemplatesDone.forEach(item => {
                if (item._id === this.conditionTempId) {
                  item.extractionStatus = 'extraction'
                }
              })
            }
//            }
            const list = res.list || []
            if (list.length === 0) {
              if (res.more) {
                this.turnPageCall(1)
              } else {
                if (!res.count) {
                  // 第一页且count为0是不再发请求
                  this.callCurPage = 1
                } else {
                  let page = Math.ceil(res.count / data.pageSize)
                  this.turnPageCall(page)
                  return false
                }
              }
            }
            this.tableData = res.list
            this.tableDataHeader = res.tableHeader
          })
        }
      },
      queryList () {
        if (this.curQualilyType === 'qualityWebchat') {
          this.webCurPage = 1
        } else {
          this.callCurPage = 1
        }
        this.searchByCoditionTemBtn()
      },
//      查询按钮
      searchByCoditionTemBtn () {
        if (this.conditionTemValue === -1) {
          this.$message.error(this.$t('qualityCheck.chooseRandomTem'))
          return
        }
        if (this.qualityConditionTemplatesDone.length === 0) {
          this.$message.error(this.$t('qualityCheck.pleaseAddTempl'))
          return
        }
        this.searchByCoditionTem()
      },
//      重新抽取
      resetSearchByCoditionTemBtn () {
        if (this.conditionTemValue === -1) {
          this.$message.error(this.$t('qualityCheck.chooseRandomTem'))
          return
        }
        if (this.qualityConditionTemplatesDone.length === 0) {
          this.$message.error(this.$t('qualityCheck.pleaseAddTempl'))
          return
        }
        let tempPageWeb = this.webCurPage
        let tempPageCall = this.callCurPage
        this.webchatDataIdList = {}
        this.callDataIdList = {}
        this.resetState = true
        if (this.curQualilyType === 'qualityWebchat') {
          this.webCurPage = 1
          if (tempPageWeb === 1) {
            this.searchByCoditionTem()
          }
        } else {
          this.callCurPage = 1
          if (tempPageCall === 1) {
            this.searchByCoditionTem()
          }
        }
      },
//      翻页查询在线
      turnPageWebchat (pageNum) {
        this.webCurPage = pageNum
        this.searchByCoditionTem()
      },
      //      翻页查询通话
      turnPageCall (pageNum) {
        this.callCurPage = pageNum
        this.searchByCoditionTem()
      },
//      查看日志
      look (_id) {
        this.paginationRecord.currentPage = 1
        this.countRecord = 0
        this.totalPageRecord = 0
        if (this.curQualilyType === 'qualityWebchat') {
          this.queryRecordWebchatSessionLog(_id, 1)
        } else {
          this.queryRecordCallListenLog(_id, 1)
        }
      },
      turnPageRecord (pageNum) {
        if (this.curQualilyType === 'qualityWebchat') {
          this.queryRecordWebchatSessionLog(this.currentId, pageNum)
        } else {
          this.queryRecordCallListenLog(this.currentId, pageNum)
        }
      },
      queryRecordCallListenLog (_id, page) {
        this.currentId = _id
        this.title = this.$t('qualityCheck.callQualityLookLog')
        this.listenpp = this.$t('qualityCheck.checkPeople')
        this.listenTime = this.$t('qualityCheck.checkTime1')
        this.$store.dispatch('queryRecordCallListenLog', {'CALL_SHEET_ID': _id, 'page': page, 'pageSize': 10}).then(() => {
          this.recordList = this.$store.state.qualityCheck.recordList.list
          this.countRecord = this.$store.state.qualityCheck.recordList.count
          this.totalPageRecord = Math.ceil(this.$store.state.qualityCheck.recordList.count / 10) || 0
          this.isShowlooklog = true
        })
      },
      queryRecordWebchatSessionLog (_id, page) {
        this.currentId = _id
        this.title = this.$t('qualityCheck.onlineWebchatLog')
        this.listenpp = this.$t('qualityCheck.checkPeople')
        this.listenTime = this.$t('qualityCheck.checkTime1')
        this.$store.dispatch('queryRecordWebchatSessionLog', {'sessionId': _id, 'page': page, 'pageSize': 10}).then(() => {
          this.recordList = this.$store.state.qualityCheck.recordList.list
          this.countRecord = this.$store.state.qualityCheck.recordList.count
          this.totalPageRecord = Math.ceil(this.$store.state.qualityCheck.recordList.count / 10) || 0
          this.isShowlooklog = true
        })
      },
//      置换
      replacementRecord (value) {
        this.webLoading = true
        this.callLoading = true
        if (this.curQualilyType === 'qualityWebchat') {
          let data = {}
          data.user = value.user
          data.randomTemplateId = this.conditionTempId
          data.sessionId = value._id
          if (!this.webchatDataIdList[data.randomTemplateId]) {
            this.webchatDataIdList[data.randomTemplateId] = []
          }
          data.idList = this.webchatDataIdList[data.randomTemplateId]
          this.$store.dispatch('displacesTmpWebchatSession', data).then(res => {
            if (!res.success) {
              this.$message.error(this.$t('qualityCheck.replacementDataError'))
              return false
            }
            for (let ind in res.idList) {
              this.webchatDataIdList[data.randomTemplateId][ind] = res.idList[ind]
            }
            if (res.selectedId) {
              this.webchatDataIdList[data.randomTemplateId].push(res.selectedId)
            } else {
              this.$message.error(this.$t('qualityCheck.noMoreOnlineConsultationRecords'))
            }
            this.webLoading = false
            this.searchByCoditionTemBtn()
          })
        } else {
          let data = {}
          data.callId = value.CALL_SHEET_ID
          data.randomTemplate = this.conditionTempId
          if (!this.callDataIdList[data.randomTemplateId]) {
            this.callDataIdList[data.randomTemplateId] = []
          }
          data.idList = this.callDataIdList[data.randomTemplateId]
          this.$store.dispatch('queryAllConditionData', data).then(res => {
            if (!res.success) {
              this.$message.error(this.$t('qualityCheck.replacementDataError'))
              return false
            }
            for (let ind in res.idList) {
              this.callDataIdList[data.randomTemplateId][ind] = res.idList[ind]
            }
            if (res.selectedId) {
              this.callDataIdList[data.randomTemplateId].push(res.selectedId)
            } else {
              this.$message.error(this.$t('qualityCheck.noMoreCalls'))
            }
            this.callLoading = false
            this.searchByCoditionTemBtn()
          })
        }
      },
//      评分 =====================================================
      handle (data) {
        this.currentIndex = 0
        for (let i = 0; i < this.tempList.length; i++) {
          if (this.tempList[i]._id === data._id) {
            this.currentIndex = i
            break
          }
        }
        if (data.REPEAT_CALL) {
          data.repeatCall = data.REPEAT_CALL === '48h' ? this.$t('call.repeatCall48h') : this.$t('call.repeatCall24h')
        } else {
          data.repeatCall = '--'
        }
        var num = this.tempList.length - this.currentIndex
        if (num < 5) {
          setTimeout(this.getMoreQualityCheckCallSheet, 1000)
        }
        if (this.template.QUALITY_TYPE === 'qualityWebchat') {
          this.webchatDialogShow = true
          let self = this
          this.$store.dispatch('recordWebchatSessionLog', {_id: data._id})
          this.$store.dispatch('queryBusiness', {linkWebchat: data._id, sid: data.sid}).then((response) => {
            if (response && response.length > 0) {
              data.busHistory = [response[0]]
            } else {
              data.busHistory = []
            }
            this.currentItemWebchat = data
          })
          self.currentItem = data
          self.webChatIsShow = true
          bus.$emit('webchatScoreFetch')
        } else {
          this.$store.dispatch('recordListenLog', {CALL_SHEET_ID: data._id})
          this.callDialogShow = true
          this.qcResectLabel = true
          let self = this
          let pro1 = this.$store.dispatch('queryBusiness', {callId: data._id, customer: data.CUSTOMER_ID})
          let pro2 = this.$store.dispatch('getQualityedCheckCallSheet', {data: data._id})
          Promise.all([pro1, pro2]).then(([rep1, rep2]) => {
            this.recordFileName(data.FILE_SERVER, data.RECORD_FILE_NAME, data.PBX, function (url) {
              data.audio = url
              if (rep1 && rep1.length > 0) {
                data.busHistory = [rep1[0]]
              } else {
                data.busHistory = []
              }
              self.currentItemCall = data
              self.currentItemCall.LABELS = rep2.LABELS || []
              self.refreshCallGrade = Math.random()
              self.callIsShow = true
            })
          })
        }
      },
      off () {
        let play = document.getElementById('quality-autoplay_' + this.flagId + '_old')
        if (play) {
          play.pause()
        }
        this.webchatDialogShow = false
        this.callDialogShow = false
        this.qcResectLabel = false
        if (this.isSave === true) {
          this.searchByCoditionTemBtn()
        }
      },
      getMoreQualityCheckCallSheet () {
        if (this.template.QUALITY_TYPE === 'qualityWebchat') {
          let form = {}
          form.menuId = 'quality_check_query_random'
          form.templateId = this.conditionTempId
          form.reset = false
          form.pageSize = 10
          form.page = 1
          this.$store.dispatch('getMoreQualityCheckCallSheet', {data: form, tempList: this.tempList, type: 'webchat', searchType: 'random'})
        } else {
          let form = {}
          form.cdrId = 'quality_check_query_random'
          form.randomTemplate = this.conditionTempId
          form.pageSize = 10
          form.page = 1
          form.reset = false
          this.$store.dispatch('getMoreQualityCheckCallSheet', {data: form, tempList: this.tempList, type: 'call', searchType: 'random'})
        }
      },
      nextGrade () {
        this.isSave = true
        this.$store.commit('deleteGraded/qualityCheckRandom', this.currentIndex)
        this.$store.commit('deleteGraded/qualityCheckRandom', 1)
        if (this.tempList.length <= 0) {
          this.$message.success(this.$t('qualityCheck.allRatingFinish'))
          this.webchatDialogShow = false
          this.callDialogShow = false
          this.searchByCoditionTemBtn()
        } else {
          this.$message.success(this.$t('qualityCheck.nextGrade'))
          this.handle(this.tempList[0])
        }
      },
      saveGrade (gradeObj, SQlabel, monitorType) {
        this.isSave = true
        this.$store.commit('deleteGraded/qualityCheckRandom', this.currentIndex)
        if (this.template.QUALITY_TYPE === 'qualityWebchat') {
          let data = deepClone(gradeObj)
          data._id = this.currentItem._id
          data.TEMPLATE = this.template._id
          data.values = gradeObj.obj
          let self = this
          data.isQualityCheck = true
          this.$store.dispatch('saveWebchatSheetGrade', {data, currentItem: this.currentItem}).then((res) => {
            if (res.success) {
              self.webchatDialogShow = false
              this.$store.commit('deleteGraded/qualityCheckRandom', 1)
              if (self.tempList.length <= 0) {
                self.$message.success(this.$t('qualityCheck.allRatingFinish'))
                this.searchByCoditionTemBtn()
              } else {
                self.$message.success(this.$t('qualityCheck.rateSuccessNext'))
                this.handle(self.tempList[0])
              }
            }
          })
        } else if (this.template.type === 'pass') {
          let data = {}
          data.CALL_SHEET_ID = this.currentItemCall.CALL_SHEET_ID
          gradeObj.config.amount = gradeObj.grade.amount
          data.QUALITY_GRADE = gradeObj.config
          data.COMMENTS = gradeObj.grade.COMMENT
          let GRADE_DATA = {}
          GRADE_DATA._id = this.currentItemCall._id
          GRADE_DATA.OFFERING_TIME = this.currentItemCall.OFFERING_TIME
          GRADE_DATA.DISPOSAL_AGENT = this.currentItemCall.DISPOSAL_AGENT
          GRADE_DATA.CALL_NO = this.currentItemCall.CALL_NO
          GRADE_DATA.CALLED_NO = this.currentItemCall.CALLED_NO
          GRADE_DATA.CONNECT_TYPE = this.currentItemCall.CONNECT_TYPE
          GRADE_DATA.ERROR_MEMO = this.currentItemCall.ERROR_MEMO
          GRADE_DATA.CALL_TIME_LENGTH = this.currentItemCall.CALL_TIME_LENGTH
          GRADE_DATA.FILE_SERVER = this.currentItemCall.FILE_SERVER
          GRADE_DATA.RECORD_FILE_NAME = this.currentItemCall.RECORD_FILE_NAME
          GRADE_DATA.INVESTIGATE = this.currentItemCall.INVESTIGATE
          GRADE_DATA.GRADE_AMOUNT = gradeObj.config
          GRADE_DATA.COMMENTS = gradeObj.COMMENT
          GRADE_DATA.TEMPLATE = this.template._id
          GRADE_DATA.SQ_LABEL = SQlabel
          GRADE_DATA.monitorType = monitorType
          GRADE_DATA.QC_SUBMIT = false  //   系统抽取 false   座席提交  true
          data.GRADE_DATA = GRADE_DATA
          data.SQ_LABEL = SQlabel
          data.MONITOR_TYPE = monitorType
          let self = this
          this.$store.dispatch('saveCallShellGrade', {data}).then((res) => {
            if (res && res.success) {
              self.callDialogShow = false
              self.qcResectLabel = false
              this.$store.commit('deleteGraded/qualityCheckRandom', 1)
              if (self.tempList.length <= 0) {
                self.$message.success(this.$t('qualityCheck.allRatingFinish'))
                this.searchByCoditionTemBtn()
              } else {
                self.$message.success(this.$t('qualityCheck.rateSuccessNext'))
                this.handle(self.tempList[0])
              }
            }
          })
        } else {
          let data = {}
          data.CALL_SHEET_ID = this.currentItemCall.CALL_SHEET_ID
          data.QUALITY_GRADE = gradeObj.grade
          data.COMMENTS = gradeObj.COMMENT
          let GRADE_DATA = {}
          GRADE_DATA._id = this.currentItemCall._id
          GRADE_DATA.OFFERING_TIME = this.currentItemCall.OFFERING_TIME
          GRADE_DATA.DISPOSAL_AGENT = this.currentItemCall.DISPOSAL_AGENT
          GRADE_DATA.CALL_NO = this.currentItemCall.CALL_NO
          GRADE_DATA.CALLED_NO = this.currentItemCall.CALLED_NO
          GRADE_DATA.CONNECT_TYPE = this.currentItemCall.CONNECT_TYPE
          GRADE_DATA.ERROR_MEMO = this.currentItemCall.ERROR_MEMO
          GRADE_DATA.CALL_TIME_LENGTH = this.currentItemCall.CALL_TIME_LENGTH
          GRADE_DATA.FILE_SERVER = this.currentItemCall.FILE_SERVER
          GRADE_DATA.RECORD_FILE_NAME = this.currentItemCall.RECORD_FILE_NAME
          GRADE_DATA.INVESTIGATE = this.currentItemCall.INVESTIGATE
          GRADE_DATA.GRADE_AMOUNT = gradeObj.grade
          GRADE_DATA.COMMENTS = gradeObj.COMMENT
          GRADE_DATA.TEMPLATE = this.template._id
          GRADE_DATA.SQ_LABEL = SQlabel
          GRADE_DATA.monitorType = monitorType
          GRADE_DATA.QC_SUBMIT = false  //   系统抽取 false   座席提交  true
          data.SQ_LABEL = SQlabel
          data.MONITOR_TYPE = monitorType
          for (let i in gradeObj.obj) {
            GRADE_DATA[i] = gradeObj.obj[i]
          }
          data.GRADE_DATA = GRADE_DATA

          let self = this
          this.$store.dispatch('saveCallGradeForScore', {data}).then((res) => {
            if (res.success) {
              self.callDialogShow = false
              self.qcResectLabel = false
              // 删除tempList评价完的那个
              this.$store.commit('deleteGraded/qualityCheckRandom', 1)
              if (self.tempList.length <= 0) {
                self.$message.success(this.$t('qualityCheck.allRatingFinish'))
                this.searchByCoditionTemBtn()
              } else {
                self.$message.success(this.$t('qualityCheck.rateSuccessNext'))
                this.handle(self.tempList[0])
              }
            }
          })
        }
      },
      recordFileName (server, name, pbx, callBack) {
        if (!server) {
          callBack('')
          return
        }
        if (server.indexOf('record.7moor.com') > -1 || server.indexOf('m7-record.oss-cn-hangzhou') > -1 || server.indexOf('aliyuncs.com') > -1) {
          server = 'https' + server.substr(server.indexOf(':'), server.length)
          callBack(server + '/' + name)
        } else if (document.location.protocol === 'https:') {
          if (pbx) {
            getCache('accountPbx', pbx, this, function (pbxObj) {
              if (pbxObj) {
                if (pbxObj.assDomain) {
                  let assDomain = pbxObj.assDomain
                  if (assDomain.substr(assDomain.length - 1, assDomain.length) === '/') {
                    assDomain = assDomain.substr(0, assDomain.length - 1)
                  }
                  server = assDomain
                }
              }
              callBack(server + '/' + name)
            })
          } else {
            callBack(server + '/' + name)
          }
        } else {
          callBack(server + '/' + name)
        }
      },
//      评分 end=============================================
      setHeaderConfig () {
        if (this.template.QUALITY_TYPE !== 'qualityWebchat') {
          this.$store.dispatch('getReportTableHeader', 'quality_call_table_title').then((res) => {
            this.headOptions = res
            this.tableConfigType = 'quality_call_table_title'
            this.isShowTableConfig = !this.isShowTableConfig
          })
        } else {
          this.$store.dispatch('getReportTableHeader', 'quality_webchat_table_title').then((res) => {
            this.headOptions = res
            this.tableConfigType = 'quality_webchat_table_title'
            this.isShowTableConfig = !this.isShowTableConfig
          })
        }
      },
      closeTableConfig (data) {
        this.isShowTableConfig = false
        if (data === 'save') {
          this.searchByCoditionTemBtn()
        }
      }
    },
    computed: {
      count () {
        return this.$store.state.qualityCheck.searchListRandom.count
      },
      totalPage () {
        return Math.ceil(this.$store.state.qualityCheck.searchListRandom.count / 10) || 1
      },
//      tableData () {
//        return this.$store.state.qualityCheck.searchListRandom.list
//      },
      tempList () {
        return this.$store.state.qualityCheck.tempListRandom
      }
    },
    beforeMount () {
      this.beforeMountState = true
      this.fetchData()
      if (isHasFunc('func_call_quality_agent', this.$store.state.session.user)) {
        this.callAgentShow = true
      }
    },
    activated () {
//      this.conditionTemValue = -1
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .condition
    height calc(100vh - 158px)
    padding 20px 20px 0
    overflow scroll
    .wd100
      width 100px
      text-align left
      margin-bottom 6px
      /*display inline-block*/
    .random-elrow
      margin-top 20px
    .top
      .term
        .addOrDel
          margin-left 20px
          display inline-block
          padding 4px
          border-radius 2px
          font-size 12px
          cursor pointer
          .iconfont
            font-size 12px
      .temp
        display inline-block
        margin-bottom 20px
      .el-radio
        margin-left 20px
      .temp
        color $cf-gray1
      .condition-temp-show-wrap
        .condition-temp-show-webchat
        .condition-temp-show-call
          .condition-temp-con
            width 100%
            display inline-block
            vertical-align top
            .condition-temp-con-detail
              display inline-block
              width 100%
              border 1px solid #ddd
              border-radius 4px
              background-color #fafafa
              padding 6px
              height 16px
              line-height 16px
              margin-right 10px
              vertical-align middle
              overflow hidden
              text-overflow ellipsis
              overflow hidden
              white-space  nowrap
            .con-lable
              padding 4px 40px
              background-color $c-main
              display inline-block
              color $cf-white
              border-radius 4px
              margin-left 6px
              margin-bottom 6px
            .wd60
              width 60px
            .wd400
              width 26%
          .condition-temp-con-first-line
            width 100%
          .condition-temp-con-last-line
            min-width 600px
            .el-checkbox
              margin-left 20px
      .sub
        text-align right
        margin-top 10px
        .rest
        .search
          display inline-block
          width 90px
          height 30px
          cursor pointer
          text-align center
        .search
          margin-left 24px
    .tables
      padding-bottom 30px
      .deploy
        height 48px
        line-height 48px
        color #989898
        border 1px solid #ebebeb
        border-bottom none
        padding-left 14px
        .fr
          padding-top 10px
          height 38px
        .table-header-config
          float left
          line-height 42px
          .iconfont
            font-size 18px
            color $c-main
            float left
          .tex
            cursor pointer
            margin-left 10px
            color #000
    .ui-affix
      margin-top 20px
      /*padding-bottom 0*/
    .looklog
      .search-pagination
        float right
        height 48px
        .page
          margin-top 10px
          .el-pagination
            padding 0
  .second
    float right
  .ui-unfold-span
    cursor pointer
    color $c-main
    margin-left 20px
</style>
